import { defineStore } from "pinia";
import axios from "axios"; // 假设你使用的是 Axios
import { EncryptStorage } from "encrypt-storage";
//需注意使用stateManagementUse
export const encryptStorage = new EncryptStorage("YM1234567890", {
  stateManagementUse: true,
});
export interface UserInfo {
  id: number;
  username: string;
  mobile: string;
  last_time: string;
  last_ip: string;
  token: string;
  refreshToken: string;
  money: string;
  score: string;
  avatar: string;
  label_id: string;
  isSetPwd: boolean;
  email: string;
  user_type: number;
  regDay: number;
  expiration_time: string;
}

export const useUserInfo = defineStore("userInfo", {
  state: (): UserInfo => {
    return {
      id: 0,
      username: "",
      mobile: "",
      last_time: "",
      last_ip: "",
      token: "",
      refreshToken: "",
      money: "",
      score: "",
      avatar: "",
      label_id: "",
      isSetPwd: false,
      email: "",
      user_type: 0,
      regDay: 0,
      expiration_time: "",
    };
  },
  actions: {
    async fetchUserInfo() {
      try {
        const token = this.token;
        // 假设你的 API 端点是 /api/user/{userId}
        const response = await axios.get(`api/v1/profile`, {
          headers: {
            token: `${token}`, // 假设你的 API 使用 Bearer tokens
          },
        });
        // // 假设 API 返回的数据结构与你定义的 UserInfo 接口匹配
        const userInfo: UserInfo = response.data.data.list;
        // // 更新 store 中的状态
        this.$patch(userInfo); // 使用 $patch 方法可以更安全地更新状态
      } catch (error) {
        console.error("Error fetching user info:", error);
        // 处理错误，例如显示错误消息或重置状态
      }
    },
    removeToken() {
      this.token = "";
      this.refreshToken = "";
    },
    dataFill(state: UserInfo) {
      this.$state = { ...this.$state, ...state };
    },
    setToken(token: string, type: "auth" | "refresh") {
      const field = type == "auth" ? "token" : "refreshToken";
      this[field] = token;
    },
    getToken(type: "auth" | "refresh" = "auth") {
      return type === "auth" ? this.token : this.refreshToken;
    },
    logout() {},
    isLogin() {
      return this.id && this.token;
    },
  },
  persist: {
    enabled: true,
    key: "userInfo", //如果需要对存储的密钥key进行命名
    storage: encryptStorage,
    // storage: localStorage, //如果不使用加密处理
    paths: ["userInfo"],
  },
});
